import { Router } from 'express'
import { auth, role } from '../middleware/auth.js'
import { Leave } from '../models/Leave.js'
import { loadLeave, ensureStudentOwnsLeave } from '../middleware/permission.js'

const router = Router()

router.use(auth, role('student'))

router.get('/leaves', async (req, res, next) => {
  try {
    const {
      status,
      type,
      page = 1,
      pageSize = 10,
      sortBy = 'created_at',
      sortOrder = 'desc',
    } = req.query

    const result = await Leave.findAll({
      studentId: req.user.id,
      status,
      type,
      page: Number(page),
      limit: Math.min(100, Number(pageSize)),
      sortBy,
      order: sortOrder,
    })

    res.json({
      code: 0,
      message: 'ok',
      data: {
        total: result.total,
        page: result.page,
        pageSize: result.limit,
        rows: result.list,
      },
    })
  } catch (error) {
    next(error)
  }
})

router.post('/leaves', async (req, res, next) => {
  try {
    const { type, startAt, endAt, reason } = req.body || {}
    if (!type || !startAt || !endAt || !reason)
      return res.status(400).json({ code: 400, message: '参数不完整' })

    const item = await Leave.create({
      studentId: req.user.id,
      type,
      startAt,
      endAt,
      reason,
    })

    res.json({ code: 0, message: 'ok', data: item })
  } catch (error) {
    next(error)
  }
})

router.get('/leaves/:id', loadLeave, ensureStudentOwnsLeave, async (req, res, next) => {
  try {
    res.json({ code: 0, message: 'ok', data: req.leave })
  } catch (error) {
    next(error)
  }
})

router.delete('/leaves/:id', loadLeave, ensureStudentOwnsLeave, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const item = req.leave

    if (item.status !== 'pending')
      return res.status(409).json({ code: 409, message: '只能撤销待审批的申请' })

    await Leave.updateStatus(id, 'cancelled')
    res.json({ code: 0, message: '撤销成功' })
  } catch (error) {
    next(error)
  }
})

export default router
